package com.project.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;

@Component
@Aspect
public class ServiceProxy {
    private static SqlSessionFactory factory;
    static{
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object around(ProceedingJoinPoint pointer){
        Object returnObj = null;
        //得到session对象
        SqlSession session = factory.openSession();
        try {
            //得到目标对象
            Object targetObj = pointer.getTarget();
            //得到目标对象的属性列表
            Field[] farray = targetObj.getClass().getDeclaredFields();
            for (Field f : farray) {
                if (f.getType().isInterface()) {//判断属性是否为接口类型
                    f.setAccessible(true);
                    //得到接口实现类对象
                    Object mapperObj = session.getMapper(f.getType());
                    //将mapper属性实例化
                    f.set(targetObj, mapperObj);
                }
            }

            //执行目标方法，得到目标方法执行后的返回值
            returnObj = pointer.proceed();

            //提交事务
            session.commit();

        }catch (Throwable e){
            e.printStackTrace();
            //回滚事务
            session.rollback();
        }finally{
            session.close();
        }

        return returnObj;
    }
}
